import React, { useState, memo } from "react";
import { Card, DatePicker, Button, Upload, Progress, message } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import styles from "./style.module.less";
import { trainWaterModel, trainParamsModel } from "@/apis/TrainModel";

const { RangePicker } = DatePicker;

const TrainModel = () => {
  // 独立管理来料水分预测模型的状态
  const [waterModel, setWaterModel] = useState({
    file: null,
    timeRange: [],
    trainingTime: null,
    completionTime: null, // 新增完成时间字段
    progress: 0,
    loading: false,
  });

  // 独立管理烘丝机参数预测模型的状态
  const [paramsModel, setParamsModel] = useState({
    file: null,
    timeRange: [],
    trainingTime: null,
    completionTime: null, // 新增完成时间字段
    progress: 0,
    loading: false,
  });

  // 上传文件校验
  const beforeUpload = (file, modelType) => {
    const isExcel =
      file.type === "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
      file.type === "application/vnd.ms-excel";
    if (!isExcel) {
      message.error("只能上传Excel文件(.xls或.xlsx)！");
      return Upload.LIST_IGNORE;
    }
    // 根据模型类型更新文件
    if (modelType === "water") {
      setWaterModel((prev) => ({ ...prev, file }));
    } else if (modelType === "params") {
      setParamsModel((prev) => ({ ...prev, file }));
    }
    return false; // 手动上传文件，不自动上传
  };

  // 模拟训练进度条
  const simulateProgress = (modelType, callback) => {
    let progress = 0;
    const interval = setInterval(() => {
      if (progress >= 100) {
        clearInterval(interval);
        callback(); // 进度完成后执行回调
      } else {
        progress += 10;
        if (modelType === "water") {
          setWaterModel((prev) => ({ ...prev, progress }));
        } else if (modelType === "params") {
          setParamsModel((prev) => ({ ...prev, progress }));
        }
      }
    }, 500); // 每 0.5 秒更新一次
  };

  // 获取当前时间并格式化
  const getCurrentTime = () => {
    const now = new Date();
    return now.toLocaleString("zh-CN", { hour12: false }); // 格式化为 24 小时制
  };

  // 开始训练处理逻辑
  const handleStartTraining = async (modelType, apiFunction) => {
    const modelState = modelType === "water" ? waterModel : paramsModel;
    const { file, timeRange } = modelState;

    // 检查文件是否上传
    if (!file) {
      message.warning("请先上传文件！");
      return;
    }
    // 检查时间段是否选择
    if (timeRange.length !== 2) {
      message.warning("请先选择时间段！");
      return;
    }

    const [start, end] = timeRange;
    const formData = new FormData();
    formData.append("file", file);
    formData.append("start_time", start.format("YYYY-MM-DD HH:mm:ss"));
    formData.append("end_time", end.format("YYYY-MM-DD HH:mm:ss"));

    try {
      // 开始加载并初始化进度条
      if (modelType === "water") {
        setWaterModel((prev) => ({ ...prev, loading: true, progress: 0 }));
      } else if (modelType === "params") {
        setParamsModel((prev) => ({ ...prev, loading: true, progress: 0 }));
      }

      // 模拟进度条完成后调用后端接口
      simulateProgress(modelType, async () => {
        try {
          // 调用后端接口
          const response = await apiFunction(formData);

          // 打印后端返回的数据进行调试
          console.log(`Response from ${modelType} model:`, response.data);

          // 如果后端返回错误 "Too little training data!"
          if (response.data.error === "Too little training data!") {
            message.warning("所选数据量过少，请重新选择更长的时间段或更多的数据！");
            return;
          }

          // 获取训练时间和完成时间
          const trainingTime = response.data["trainingTime"]; // 从后端获取训练时间
          const completionTime = getCurrentTime(); // 获取当前时间

          // 更新模型状态
          if (modelType === "water") {
            setWaterModel((prev) => ({
              ...prev,
              trainingTime: `${trainingTime} 秒`,
              completionTime, // 保存完成时间
              loading: false,
            }));
            message.success("来料水分预测完成！");
          } else if (modelType === "params") {
            setParamsModel((prev) => ({
              ...prev,
              trainingTime: `${trainingTime} 秒`,
              completionTime, // 保存完成时间
              loading: false,
            }));
            message.success("烘丝机参数预测完成！");
          }
        } catch (error) {
          console.error("请求失败:", error);
          message.error("训练数据过少，请选择其他时间段或者数据！");
        }
      });
    } catch (error) {
      console.error("训练失败：", error);
      // 清除加载状态
      if (modelType === "water") {
        setWaterModel((prev) => ({ ...prev, loading: false }));
      } else if (modelType === "params") {
        setParamsModel((prev) => ({ ...prev, loading: false }));
      }
      message.error("训练失败，请检查参数或稍后重试！");
    }
  };

  return (
    <div className={styles.trainModelContainer}>
      <div className={styles.cardContainer}>
        {/* 来料水分预测模型 */}
        <Card title="来料水分预测模型" className={styles.card}>
          <div className={styles.formGroup}>
            输入训练数据：
            <Upload
              beforeUpload={(file) => beforeUpload(file, "water")}
              showUploadList={true}
              maxCount={1}
            >
              <Button icon={<UploadOutlined />}>点击上传文件</Button>
            </Upload>
          </div>
          <div className={styles.formGroup}>
            选择时间段：
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              onChange={(dates) => setWaterModel((prev) => ({ ...prev, timeRange: dates }))}
            />
          </div>
          <Button
            type="primary"
            className={styles.trainButton}
            onClick={() => handleStartTraining("water", trainWaterModel)}
          >
            开始训练
          </Button>
          <div className={styles.trainingStatus}>
            <Progress percent={waterModel.progress} />
            {waterModel.trainingTime && (
              <>
                <div>训练耗时：{waterModel.trainingTime}</div>
                <div>完成时间：{waterModel.completionTime}</div>
              </>
            )}
          </div>
        </Card>

        {/* 烘丝机参数预测模型 */}
        <Card title="烘丝机参数预测模型" className={styles.card}>
          <div className={styles.formGroup}>
            输入训练数据：
            <Upload
              beforeUpload={(file) => beforeUpload(file, "params")}
              showUploadList={true}
              maxCount={1}
            >
              <Button icon={<UploadOutlined />}>点击上传文件</Button>
            </Upload>
          </div>
          <div className={styles.formGroup}>
            选择时间段：
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              onChange={(dates) => setParamsModel((prev) => ({ ...prev, timeRange: dates }))}
            />
          </div>
          <Button
            type="primary"
            className={styles.trainButton}
            onClick={() => handleStartTraining("params", trainParamsModel)}
          >
            开始训练
          </Button>
          <div className={styles.trainingStatus}>
            <Progress percent={paramsModel.progress} />
            {paramsModel.trainingTime && (
              <>
                <div>训练耗时：{paramsModel.trainingTime}</div>
                <div>完成时间：{paramsModel.completionTime}</div>
              </>
            )}
          </div>
        </Card>
      </div>
    </div>
  );
};

export const MemoTrainModel = memo(TrainModel);
